package com.pond.auth.util.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("aliyunSmsSender")
public class AliyunSmsSender implements SmsSender {

    @Value("${sms.aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${sms.aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${sms.aliyun.signName}")
    private String signName;

    @Value("${sms.aliyun.templateCode}")
    private String templateCode;

    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    @Override
    public boolean sendCode(String phone, String code) {
        try {
            Client client = createClient();
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse response = client.sendSms(request);
            System.out.println("短信响应：" + response.getBody().getCode());
            System.out.println("错误信息：" + response.getBody().getMessage());
            return "OK".equalsIgnoreCase(response.getBody().getCode());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
